package cn.edu.hznu.util.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

public class ForkJoinExample extends RecursiveTask<Integer>{
	
	private final static int THERSHOLD = 2;
	private int start;
	private int end;
	
	public ForkJoinExample(int start, int end) {
		this.start = start;
		this.end = end;
	}
	
	@Override
	protected Integer compute() {
		int sum = 0;
		
		boolean canCompute = (end - start) <= THERSHOLD;
		if (canCompute) {
			sum = IntStream.of(start, end + 1).sum();
//			for (int i = start; i <= end; i++) {
//				sum += i;
//			}
		} else {
			int middle = (end - start) / 2;
			ForkJoinExample leftTask = new ForkJoinExample(start, middle);
			ForkJoinExample rightTask = new ForkJoinExample(middle + 1, end);
			leftTask.fork();
			rightTask.fork();
			sum = leftTask.join() + rightTask.join();
		}
		return sum;
	}
	
	public static void main(String[] args) {
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoinExample forkJoinTask = new ForkJoinExample(1, 4);
		Future<Integer> result = forkJoinPool.submit(forkJoinTask);
		
		try {
			System.out.println(result.get().intValue());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		
	}

}
